import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 更新监控系统以支持TooBit API和鉴权功能
 * 
 * @author TooBit
 * @date 2025-01-06
 */
public class UpdateMonitoringSystemForTooBitAPI {
    
    private static final String DB_URL = "jdbc:mysql://db.test1.wcsbapp.com:3306/ChainUp?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=GMT%2B8";
    private static final String DB_USER = "chainup_test";
    private static final String DB_PASSWORD = "fRR#$er234N";
    
    public static void main(String[] args) {
        System.out.println("🚀 === 更新TooBit监控系统API配置 ===");
        System.out.println("");
        
        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // 连接数据库
            Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            System.out.println("✅ 数据库连接成功");
            
            // 1. 添加API鉴权配置到sys_config表
            addAPIAuthConfig(connection);
            
            // 2. 更新现有的WebSocket和API配置
            updateAPIEndpoints(connection);
            
            // 3. 创建API鉴权日志表
            createAPIAuthLogTable(connection);
            
            connection.close();
            System.out.println("");
            System.out.println("🎉 === 更新完成 ===");
            System.out.println("");
            System.out.println("📋 更新内容:");
            System.out.println("   ✅ 添加TooBit API鉴权配置");
            System.out.println("   ✅ 更新API端点为api.toobit.com");
            System.out.println("   ✅ 创建API鉴权日志表");
            System.out.println("   ✅ 配置默认鉴权参数");
            System.out.println("");
            System.out.println("🔧 下一步操作:");
            System.out.println("   1. 重启后端服务以加载新配置");
            System.out.println("   2. 更新监控控制器以使用新的鉴权工具类");
            System.out.println("   3. 测试各个监控模块的API调用");
            
        } catch (Exception e) {
            System.out.println("❌ 更新失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static void addAPIAuthConfig(Connection connection) throws Exception {
        System.out.println("📝 添加API鉴权配置...");
        
        // 添加TooBit API配置
        String[] configs = {
            "INSERT INTO sys_config (config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark) VALUES " +
            "('TooBit API基础URL', 'toobit.api.base.url', 'https://api.toobit.com', 'Y', 'admin', NOW(), 'admin', NOW(), 'TooBit API的基础URL')",
            
            "INSERT INTO sys_config (config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark) VALUES " +
            "('TooBit API Access Key', 'toobit.api.access.key', '4gUihctRvu3td8iUyvgfnK4m6HzUyTDDg4zO2hwfFfXyz9DDy2ZDFzIfrCLcYucu', 'Y', 'admin', NOW(), 'admin', NOW(), 'TooBit API访问密钥')",
            
            "INSERT INTO sys_config (config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark) VALUES " +
            "('TooBit API Secret Key', 'toobit.api.secret.key', '6REmc8JHbkDlyp8kQ971FRPb2CNVlBl4ACRxpvnZawYssDfkJBeK1m4C9ts4186R', 'Y', 'admin', NOW(), 'admin', NOW(), 'TooBit API密钥')",
            
            "INSERT INTO sys_config (config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark) VALUES " +
            "('API请求时间窗口', 'toobit.api.recv.window', '5000', 'Y', 'admin', NOW(), 'admin', NOW(), 'API请求时间窗口(毫秒)')",
            
            "INSERT INTO sys_config (config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark) VALUES " +
            "('启用API鉴权', 'toobit.api.auth.enabled', 'true', 'Y', 'admin', NOW(), 'admin', NOW(), '是否启用API鉴权功能')",
            
            "INSERT INTO sys_config (config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark) VALUES " +
            "('默认鉴权类型', 'toobit.api.default.auth.type', 'MARKET_DATA', 'Y', 'admin', NOW(), 'admin', NOW(), '默认API鉴权类型')"
        };
        
        for (String config : configs) {
            try {
                PreparedStatement stmt = connection.prepareStatement(config);
                stmt.executeUpdate();
                stmt.close();
                System.out.println("   ✅ 添加配置成功");
            } catch (Exception e) {
                // 忽略重复键错误
                if (!e.getMessage().contains("Duplicate entry")) {
                    throw e;
                }
                System.out.println("   ⚠️ 配置已存在，跳过");
            }
        }
    }
    
    private static void updateAPIEndpoints(Connection connection) throws Exception {
        System.out.println("🔄 更新API端点配置...");
        
        // 更新现货监控常量（如果有数据库配置表的话）
        String[] updates = {
            "UPDATE sys_config SET config_value = 'https://api.toobit.com' WHERE config_key = 'spot.api.base.url'",
            "UPDATE sys_config SET config_value = 'wss://ws.toobit.com/ws-api/v1' WHERE config_key = 'spot.websocket.base.url'"
        };
        
        for (String update : updates) {
            try {
                PreparedStatement stmt = connection.prepareStatement(update);
                int affectedRows = stmt.executeUpdate();
                stmt.close();
                if (affectedRows > 0) {
                    System.out.println("   ✅ 更新端点配置成功");
                } else {
                    System.out.println("   ⚠️ 未找到相关配置，跳过");
                }
            } catch (Exception e) {
                System.out.println("   ⚠️ 更新端点配置失败: " + e.getMessage());
            }
        }
    }
    
    private static void createAPIAuthLogTable(Connection connection) throws Exception {
        System.out.println("📊 创建API鉴权日志表...");
        
        String createTableSQL = 
            "CREATE TABLE IF NOT EXISTS `api_auth_log` (" +
            "  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID'," +
            "  `request_url` varchar(500) DEFAULT NULL COMMENT '请求URL'," +
            "  `auth_type` varchar(20) DEFAULT NULL COMMENT '鉴权类型'," +
            "  `api_key` varchar(100) DEFAULT NULL COMMENT 'API Key (脱敏)'," +
            "  `request_timestamp` bigint(20) DEFAULT NULL COMMENT '请求时间戳'," +
            "  `response_code` int(11) DEFAULT NULL COMMENT '响应状态码'," +
            "  `response_time` bigint(20) DEFAULT NULL COMMENT '响应时间(毫秒)'," +
            "  `success` tinyint(1) DEFAULT '0' COMMENT '是否成功'," +
            "  `error_message` text COMMENT '错误信息'," +
            "  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'," +
            "  PRIMARY KEY (`id`)," +
            "  KEY `idx_request_timestamp` (`request_timestamp`)," +
            "  KEY `idx_auth_type` (`auth_type`)," +
            "  KEY `idx_success` (`success`)," +
            "  KEY `idx_create_time` (`create_time`)" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='API鉴权日志表'";
        
        try {
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(createTableSQL);
            stmt.close();
            System.out.println("   ✅ API鉴权日志表创建成功");
        } catch (Exception e) {
            if (e.getMessage().contains("already exists")) {
                System.out.println("   ⚠️ API鉴权日志表已存在");
            } else {
                throw e;
            }
        }
        
        // 插入一些测试数据
        String insertSQL = 
            "INSERT INTO api_auth_log (request_url, auth_type, api_key, request_timestamp, response_code, response_time, success, error_message) VALUES " +
            "('https://api.toobit.com/api/v1/exchangeInfo', 'NONE', NULL, ?, 200, 150, 1, NULL), " +
            "('https://api.toobit.com/api/v1/exchangeInfo', 'MARKET_DATA', '4gUihctRvu***', ?, 200, 180, 1, NULL), " +
            "('https://api.toobit.com/api/v1/exchangeInfo', 'USER_DATA', '4gUihctRvu***', ?, 200, 220, 1, NULL)";
        
        try {
            PreparedStatement stmt = connection.prepareStatement(insertSQL);
            long now = System.currentTimeMillis();
            stmt.setLong(1, now - 10000);
            stmt.setLong(2, now - 5000);
            stmt.setLong(3, now);
            stmt.executeUpdate();
            stmt.close();
            System.out.println("   ✅ 插入测试日志数据成功");
        } catch (Exception e) {
            if (!e.getMessage().contains("Duplicate entry")) {
                System.out.println("   ⚠️ 插入测试数据失败: " + e.getMessage());
            }
        }
    }
}